<template>
  <div class="container">
    <el-row :gutter="5">
		<!--左树右表-->
		<el-col :span="3">
		    <el-card shadow="never">
		        <div slot="header">
		            <el-form :inline="true" size="small">
		                <el-form-item class="el-search-item">
		                    <el-input placeholder="输入关键字进行过滤" prefix-icon="el-icon-search" v-model="catTree.filterText"></el-input>
		                </el-form-item>
		            </el-form>
		        </div>
		        <div class="tree-dept">
		            <el-tree :data="catTree.treeData" :props="catTree.treeProps" :expand-on-click-node="false"  node-key="categoryId" @node-click="catTreeHandleNodeClick"
		                     :filter-node-method="catTreeFilterNode" ref="catTreeRef" default-expand-all empty-text="加载中，请稍后..." :highlight-current="true"></el-tree>
		        </div>
		    </el-card>
		</el-col>
		<el-col :span="21">
      <el-card shadow="never">
        <div slot="header">
          <el-form :inline="true" :model="searchForm" size="small">
            <el-form-item label="名称" class="el-search-item">
              <el-input v-model="searchForm.pname" placeholder="模糊查询" clearable></el-input>
            </el-form-item>
			<el-form-item label="编码" class="el-search-item">
			  <el-input v-model="searchForm.pno" placeholder="精准查询" clearable></el-input>
			</el-form-item>
            <el-form-item class="el-search-item">
              <el-button type="success" plain icon="el-icon-search" @click="getDataList">查询</el-button>
            </el-form-item>
            <el-form-item class="el-search-item">
              <el-button v-if='hasPerm("product:product:add")' type="primary" plain icon="el-icon-plus" @click="openAdd">新增</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--数据表格 element ui-->
		<el-table :data="tableData" :height="tableHeight" style="width: 100%" v-loading="tableLoading" element-loading-text="数据正在加载中...">
          <el-table-column prop="pname" label="名称" align="center" sortable  width="150"></el-table-column>
          <el-table-column prop="pno" label="编码" align="center" width="100" sortable></el-table-column>
          <el-table-column prop="seq" label="排序" align="center" sortable width="80" ></el-table-column>
          <el-table-column label="状态" align="center" sortable width="80">
			  <template slot-scope="scope">
			    <span v-if="scope.row.state==1">激活</span><span v-else>失效</span>
			  </template>
		  </el-table-column>
          <el-table-column prop="priceDw" label="单位" align="center" width="100" sortable></el-table-column>
          <el-table-column label="单价" align="center" width="80" sortable>
			  <template slot-scope="scope">
			    <span v-if="scope.row.price>0" title="单价">{{scope.row.price}}</span><br/>
				<span v-if="scope.row.priceAz>0" title="加安装的单价" style="color: blue;">{{scope.row.priceAz}}</span>
			  </template>
		  </el-table-column>
          <el-table-column label="成本" align="center" width="80" sortable>
			  <template slot-scope="scope">
			    <span v-if="scope.row.priceCb>0" title="成本单价">{{scope.row.priceCb}}</span><br/>
			  	<span v-if="scope.row.priceCbaz>0" title="加安装的成本单价" style="color: blue;">{{scope.row.priceCbaz}}</span>
			  </template>
		  </el-table-column>
          <!-- <el-table-column prop="utime" label="更新" align="center" sortable></el-table-column> -->
		  <el-table-column prop="priceDesc" label="价格说明" align="center" sortable width="120" show-overflow-tooltip></el-table-column>
		  <el-table-column label="媒体库" align="center" sortable width="210">
			  <template slot-scope="scope">
				  <div v-for="i in scope.row.productMedias" style="float:left;margin:1px;border:1px solid red;">
					  <img v-if="i.mtype==1" :src="i.url" :title="i.msg" @click="openImgUpdate(i)" width="30"/>
					  <video v-else-if="i.mtype==2" :src="i.url" :title="i.msg" @click="openImgUpdate(i)" controls="controls"></video>
				  </div>
				  <el-button v-if='hasPerm("product:productMedia:edit")' @click="openImgAdd(scope.row)" size="mini" type="text" icon="el-icon-plus">添加</el-button>
			  </template>
		  </el-table-column>
		  <el-table-column prop="msg" label="备注" align="center" sortable  show-overflow-tooltip width="120"></el-table-column>
          <el-table-column v-if='hasPerm("product:product:list")' label="更多操作" align="center" width="130">
            <template slot-scope="scope">
              <el-button v-if='hasPerm("product:product:edit")' @click="openUpdate(scope.row)" size="mini" type="text" icon="el-icon-edit">编辑</el-button>
              <el-button v-if='hasPerm("product:product:del")' @click="deleteFun(scope.row)" size="mini" type="text" icon="el-icon-delete">删除</el-button>
			  <el-button v-if='hasPerm("product:productGg:list")' @click="openGg(scope.row)" size="mini" type="text" icon="el-icon-s-operation">规格</el-button>
			  <el-button v-if='hasPerm("product:productPrice:list")' @click="openPrice(scope.row)" size="mini" type="text" icon="el-icon-price-tag">价格</el-button>
			</template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <el-pagination style="padding:0;text-align: center;" background @size-change="handleSizeChange" @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper"
                       :current-page="pageNum" :page-sizes="[10, 20, 30]" :page-size="pageSize" :total="total">
        </el-pagination>
      </el-card>
	  </el-col>
      <!--新增对话框-->
	  <el-drawer :title="dialog.dialogTitle" :visible.sync="dialog.visible" :direction="dialog.direction" :size="dialog.size" :before-close="handleClose">
      <el-row class="drawer-table">
          <el-col :span="24">
        <el-form :rules="rules" ref="productForm" :model="productForm" size="small" label-width="120px">
          <el-form-item prop="cname" label="分类">
            <el-input @click.native="catSelectDialogShow" v-model="productForm.cname" placeholder="请选择分类" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="pname" label="名称">
            <el-input v-model="productForm.pname" placeholder="请输入名称" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="pno" label="编码">
            <el-input v-model="productForm.pno" placeholder="请输入编码" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="seq" label="排序">
            <el-input v-model="productForm.seq" placeholder="请输入排序(降序)" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="state" label="状态">
			<el-radio-group v-model="productForm.state">
				<el-radio :label="1">激活</el-radio><el-radio :label="0">失效</el-radio>
			</el-radio-group>
          </el-form-item>
          <!-- <el-form-item prop="priceDw" label="单价单位">
            <el-input v-model="productForm.priceDw" placeholder="请输入单价单位" auto-complete="off"></el-input>
          </el-form-item> -->
		  <sysParameterHtml numb="price-type" @toBackFun="priceTypeSel" placeholderData="请选择单位" ref="sysParameterHtmlRef" />
          <el-form-item prop="price" label="单价">
            <el-input v-model="productForm.price" placeholder="请输入单价" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="priceAz" label="包安装单价">
            <el-input v-model="productForm.priceAz" placeholder="请输入包安装单价" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="priceCb" label="成本">
            <el-input v-model="productForm.priceCb" placeholder="请输入成本" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="priceCbaz" label="包安装成本">
            <el-input v-model="productForm.priceCbaz" placeholder="请输入包安装成本" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item prop="priceDesc" label="价格备注">
            <el-input v-model="productForm.priceDesc" placeholder="请输入价格备注" auto-complete="off" :rows="3" resize="none" type="textarea" maxlength="120"></el-input>
          </el-form-item>
          <el-form-item prop="msg" label="备注">
            <el-input v-model="productForm.msg" placeholder="请输入备注" auto-complete="off" :rows="6" resize="none" type="textarea" maxlength="120"></el-input>
          </el-form-item>
        </el-form>
		</el-col>
        </el-row>
        <el-row class="drawer-footer">
			<el-col :span="24">
				<el-button @click="dialog.visible = false" size="small">取 消</el-button>
				<el-button type="primary" @click="submitFun()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
			</el-col>
        </el-row>
        </el-drawer>
		
		<!-- 选择分类 -->
		<el-dialog title="选择分类" :visible.sync="dialogTree.visible" width="25%" top="5%">
		    <el-tree :data="catTree.treeData" :props="dialogTree.treeProps" show-checkbox  check-strictly node-key="categoryId"
		             default-expand-all :default-checked-keys="dialogTree.defKeys" ref="gcTreeRef" @check-change="catHandleNodeClick"
		             empty-text="加载中，请稍后..." style="height: 55vh;overflow: auto;"></el-tree>
		    <span slot="footer" class="dialog-footer">
		        <el-button @click="dialogTree.visible = false" size="small">取 消</el-button>
		        <el-button type="primary" @click="dialogTree.visible = false" size="small">确 定</el-button>
		    </span>
		</el-dialog>
		
		<!--新增 编辑 图片 对话框-->
		<el-drawer title="媒体库" :visible.sync="mediaDialog.visible" direction="rtl" :size="mediaDialog.size" :before-close="handleClose">
			<el-row class="drawer-table">
				<el-col :span="24">
				<el-form :rules="rulesMedia" ref="productMediaForm" :model="productMediaForm" size="small" label-width="80px">
				  <el-form-item prop="url" label="图片">
					<img class="user-img" :src="productMediaForm.url" width="330" height="auto" @click="openImageTa(productMediaForm.url)"/>
					<el-dropdown-item @click.native="uploadFun('flagImg')"><i class="fa el-icon-upload"></i>上传</el-dropdown-item>
				  </el-form-item>
					<el-form-item prop="seq" label="排序">
						<el-input v-model="productMediaForm.seq" placeholder="请输入数值" auto-complete="off"></el-input>
					</el-form-item>
				  <el-form-item prop="msg" label="说明">
				    <el-input v-model="productMediaForm.msg" placeholder="请输入说明" auto-complete="off"></el-input>
				  </el-form-item>
				</el-form>
				</el-col>
			</el-row>
			<el-row class="drawer-footer">
				<el-col :span="24">
					<el-button @click="mediaDialog.visible = false" size="small">取 消</el-button>
					<el-button type="primary" @click="submitMediaFun()" :loading="loading.status" size="small">{{loading.status ? loading.SubText : loading.BtnText}}</el-button>
				</el-col>
			</el-row>
		</el-drawer>
		<!-- 剪裁组件弹窗  标题图片 -->
		<el-dialog title="上传标题图片" :visible.sync="dialogImage.cropperModel" width="1100px">
		    <CropperImage :Name="dialogImage.cropperName" Width="400" Height="350" @uploadImgSuccess = "handleUploadSuccess" ref="child" />
		</el-dialog>
    </el-row>
  </div>
</template>
<script>
import sysParameterHtml from '@/components/glMyCom/sysParameterHtml';
import product from "@/api/product/product";
import category from "@/api/product/category";
import productMedia from "@/api/product/productMedia";
import CropperImage from "@/components/cropper/CropperImage";
export default {
	components: { sysParameterHtml,CropperImage },
    data() {
      return {
        // 表格数据
        tableData: [],
		tableLoading: false,
        // 分页数据
        total: 0,
        pageNum: 1,
        pageSize: 10,
        // 表格高度
        tableHeight: 0,
        // 用来存放日期组件所选中的值
        checkedTime: '',
        // 查询参数
        searchForm: {categoryId: null, pname: null, pno: null},
        // 弹出层
        dialog: {flag: 0, dialogTitle: "", visible: false, direction: 'rtl',size: '40%'},
		mediaDialog: {flag: 0, visible: false,size: '40%'},
		// 弹出层
		dialogTree: {treeProps: {children: 'children',label: 'cname'},defKeys: [],visible: false,},
        // 表单参数
        productForm: {
          productId: null,
          categoryId: null,cname: null,
          pname: null,
          pno: null,
          pinyin: null,
          seq: null,
          state: null,
          priceDw: null,
          price: null,
          priceAz: null,
          priceCb: null,
          priceCbaz: null,
          priceDesc: null,
          msg: null,
        },
		productMediaForm: {productMediaId: null,productId: null,seq: null,url: null,msg: null },
		dialogImage: {cropperModel: false , cropperName: '' , cropperModel: false},
		// 分类栏目
		catTree: {
			treeData: [],
			treeProps: {children: 'children',label: 'cname'},// 树形控件的属性绑定对象
			filterText: null,
			defKeys: [],// 默认选中的节点id值
		},
        // 提交按钮文字
        loading: {status: false,BtnText: '确 定',SubText: '提交中...'},
        // 表单校验
        rules: {
          categoryId: [{required: true,trigger: "change",message: "请输入种类"}],
          pname: [{required: true,max: 60,trigger: "change",message: "请输入名称,60个字以内"}],
          pno: [{required: true,trigger: "change",message: "请输入编码"}],
          seq: [{required: true,pattern: /^[1-9]\d*$/, trigger: "change",message: "请输入数字(降序)"}],
          priceDw: [{required: true,trigger: "change",message: "请输入单价单位"}],
          price: [{required: true,trigger: "change",message: "请输入单价"}],
          priceAz: [{required: true,trigger: "change",message: "请输入包安装单价"}],
          priceCb: [{required: true,trigger: "change",message: "请输入成本"}],
          priceCbaz: [{required: true,trigger: "change",message: "请输入包安装成本"}],
        },
		rulesMedia: {
		  //url: [{required: true,trigger: "change",message: "请输入路径"}],
		  seq: [{required: true,trigger: "change",message: "请输入排序"}],
		},
      };
    },
    mounted() {
      this.$nextTick(() => {
        this.tableHeight = window.innerHeight - 205;
      });
    },
    created() {
	  this.getCatTreeData();
      this.getDataList();
    },
    watch: {
		"catTree.filterText"(val) {// 监听树节点关键字过滤操作
		    this.$refs.catTreeRef.filter(val);
		}
    },
    methods: {
		handleClose(done) {
		    this.resetForm();
		    done();
		},
      handleSizeChange(val) {
        this.pageSize = val
        this.getDataList()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.getDataList()
      },
      // 获取列表
      getDataList() {
		this.tableLoading = true;
		product.list({current: this.pageNum,size: this.pageSize,categoryId: this.searchForm.categoryId,
          pname: this.searchForm.pname,pno: this.searchForm.pno}).then(res => {
          if(res.data.code === 2000) {
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
          }
		  this.tableLoading = false;
        });
      },
      // 新增按钮操作
      openAdd() {
        this.dialog.flag = 0;
        this.resetForm("productForm");
        this.dialog.dialogTitle = "新增";
		this.dialogTree.defKeys=[];
		this.productForm.productId = null;
		this.productForm.categoryId = null;
		this.productForm.cname = null;
        this.dialog.visible = true;
		if(this.$refs.gcTreeRef){
			this.$refs.gcTreeRef.setCheckedKeys([]);//设置参数选中值
		}
		if(this.$refs.sysParameterHtmlRef){
			this.$refs.sysParameterHtmlRef.inputValue = null;//设置参数选中值
		}
      },
      // 更新按钮操作
      openUpdate(row) {
        this.dialog.flag = 1;
        this.resetForm("productForm");
        this.dialog.dialogTitle = "编辑";
        this.dialog.visible = true;
		this.getById(row.productId);
      },
      // 提交数据操作
      submitFun() {
        this.$refs.productForm.validate(valid => {
          if(valid){
            this.loading.status = true;
            product.saveOrUpdate(this.productForm,this.dialog.flag).then(res => {
              if (res.data.code === 2000) {
                this.$message.success(res.data.msg);
                if(this.dialog.flag === 0){
                  this.pageNum = 1;
                }
                this.getDataList();
                // 关闭弹框
                this.dialog.visible = false;
                // 关闭加载
                this.loading.status = false;
              }else{
                this.$message.error(res.data.msg);
                this.loading.status = false;
                return false;
              }
            })
          }
        })
      },
	  // 提交数据操作
	  submitMediaFun() {
	    this.$refs.productMediaForm.validate(valid => {
	      if(valid){
	        this.loading.status = true;
	        productMedia.saveOrUpdate(this.productMediaForm,this.mediaDialog.flag).then(res => {
	          if (res.data.code === 2000) {
	            this.$message.success(res.data.msg);
	            this.getDataList();
	            this.mediaDialog.visible = false;// 关闭弹框
	            this.loading.status = false;// 关闭加载
	          }else{
	            this.$message.error(res.data.msg);
	            this.loading.status = false;
	            return false;
	          }
	        });
	      }
	    });
	  },
      // 根据id获取信息
      async getById(id) {
        const response = await product.getById(id).then(res => {
          if (res.data.code === 2000) {
            this.productForm.productId = res.data.data.productId;
            this.productForm.categoryId = res.data.data.categoryId;
			this.productForm.cname=res.data.data.cname;
            this.productForm.pname = res.data.data.pname;
            this.productForm.pno = res.data.data.pno;
            this.productForm.pinyin = res.data.data.pinyin;
            this.productForm.seq = res.data.data.seq;
            this.productForm.state = res.data.data.state;
            this.productForm.priceDw = res.data.data.priceDw;
            this.productForm.price = res.data.data.price;
            this.productForm.priceAz = res.data.data.priceAz;
            this.productForm.priceCb = res.data.data.priceCb;
            this.productForm.priceCbaz = res.data.data.priceCbaz;
            this.productForm.priceDesc = res.data.data.priceDesc;
            this.productForm.msg = res.data.data.msg;
			this.$refs.sysParameterHtmlRef.inputValue = res.data.data.priceDw;//设置参数选中值
          }
        }).catch(err => {
            this.$message({type: "error", message: "系统异常"+err});
        });
      },
      // 根据id删除
      deleteFun(row) {
        this.$confirm("确定删除当前吗？", "系统提示", {confirmButtonText: "确定", cancelButtonText: "取消", type: 'error'
        }).then(() =>{
            product.remove(row.productId).then(res => {
            if(res.data.code === 2000){
              this.$message.success(res.data.msg);
              this.getDataList()
            }else {
              this.$message.error(res.data.msg);
            }
          })
        }).catch(() => {
          this.$message.info("取消删除");
        });
      },
      // 清空表单
      resetForm(formName) {
        if (this.$refs[formName]) {
          this.$refs[formName].resetFields();
        }
      },
	  // 树节点关键字过滤
	  catTreeFilterNode(value, data) {
	      if (!value) return true;
	      return data.cname.indexOf(value) !== -1;
	  },
	  // 获取所有分类信息
	  getCatTreeData() {
	      category.list().then(res => {
	        if(res.data.code === 2000) {
	          this.catTree.treeData = res.data.data;
	        }
	      });
	  },
	  // 节点单击事件
	  catTreeHandleNodeClick(data) {
	      if(data.categoryId !== '0') {
	          this.searchForm.categoryId = data.categoryId;
	      }else {
	          this.searchForm.categoryId = null;
	      }
	      this.getDataList();
	  },
	  // 树选中分类
	  catHandleNodeClick(data, checked) {
	      if(checked === true) {
			  this.productForm.categoryId = data.categoryId;
			  this.productForm.cname=data.cname;
	  		this.$refs.gcTreeRef.setCheckedKeys([data.categoryId]);
	      } else {
	          if (this.productForm.categoryId === data.categoryId) {
	              this.$refs.gcTreeRef.setCheckedKeys([data.categoryId]);
	          }
	      }
	  },
	  // 展示选择上级分类
	  catSelectDialogShow() {
	      // 默认选中根节点
	      this.dialogTree.defKeys = [this.productForm.categoryId];
	      this.dialogTree.visible = true;
	  },
	  //选择价格单位回调
	  priceTypeSel(data){
		  this.productForm.priceDw = data;
	  },
	  openImgAdd(data){//编辑媒体库
		this.mediaDialog.flag = 0;
		this.resetForm("productMediaForm");
		this.mediaDialog.dialogTitle = "新增媒体";
		this.mediaDialog.visible = true;
		this.productMediaForm.productMediaId = null;
		this.productMediaForm.productId = data.productId;
		this.productMediaForm.url = null;
		this.productMediaForm.seq = 1;
		this.productMediaForm.msg = null;
	  },
	  openImgUpdate(row) {
	    this.mediaDialog.flag = 1;
	    this.resetForm("productMediaForm");
	    this.mediaDialog.dialogTitle = "编辑媒体";
	    this.mediaDialog.visible = true;
		this.productMediaForm.productMediaId = row.productMediaId;
		this.productMediaForm.productId = row.productId;
		this.productMediaForm.url = row.url;
		this.productMediaForm.seq = row.seq;
		this.productMediaForm.msg = row.msg;
	  },
	  // 修改头像
	  uploadFun(name) {
	      this.dialogImage.cropperName = name;
	      this.dialogImage.cropperModel = true;
	  },
	  // 图片上传成功回调
	  handleUploadSuccess (data){
	      this.dialogImage.cropperModel = false;
	      this.productMediaForm.url = data.url;
	  },
	  openImageTa(imageUrl){
		  var windowName = "_blank"; // 指定新窗口名称（"_blank"表示在新标签页或者新窗口中打开）
		  window.open(imageUrl, windowName);// 调用window.open()函数打开新窗口并加载图片
	  },
	  openGg(data){
		this.$router.push({name:'productGgList',params:{productId:data.productId}});// 通过$router.push()方法进行页面跳转到关于我们页面
		//this.$router.push({path: '/productGgList', query: {productId:data.productId}});
	  },
	  openPrice(data){
		  this.$router.push({name:'productPriceList',params:{productId:data.productId}});
		  //this.$router.push({path: '/productPriceList', query: {productId:data.productId}});
	  },
    }
  }
</script>
<style scoped>
.el-search-item {margin-bottom: 0;}
.el-card/deep/.el-card__body {padding: 0 10px 10px 10px !important;}
.el-card/deep/.el-card__header {border-bottom: none !important;padding: 10px 10px !important;}
</style>
<style>
.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{color:red;background-color: aqua;}
</style>